


<section class="content-header">
    <h1>
      义不容辞之事，当无怨无悔
      <small>乐乐的每日一句</small>
    </h1>
    <ol class="breadcrumb">
      <li><a href="#"><i class="fa fa-dashboard"></i> 项目管理</a></li>
      <li class="active">创建项目</li>
    </ol>
  </section>
  <section class="content">
  <div class="box">
    <div class="box-header">
      <h3 class="box-title">创建的项目</h3>
    </div>
    <div class="box-body">
      <table id="example2" class="table table-bordered table-hover datas">
        <thead>
          <tr>
              <th></th>
              <th>标题</th>
              <th>状态</th>
              <th>项目起始时间</th>
              <th>项目结束时间</th>
              <th>封面</th>
              <th>项目地址</th>
              <th>此项目创建时间</th>
              <th>操作</th>
          </tr>
      </thead>
      </table>
    </div>
  </div>

                    <!-- 模态框（Modal） -->
<div class="modal fade" id="editArticle" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
					项目编辑
				</h4>
			</div>
			<div class="modal-body">
       
        <div class="box box-info">
          <form class="form-horizontal" id="forms"> 
             <div class="box-body">
               <div class="form-group">
                 <label  class="col-sm-2 control-label">项目标题</label>
                 <div class="col-sm-8">
                   <input type="text" class="form-control" id="projectTitle" name="title" placeholder="文章标题">
                   <input style='display: none;' id="kind" type="text"  style="width: 0;height: 0;padding: 0;margin: 0;">
                   <input type="text" id="projectId" value="123" style="width: 0;height: 0;padding: 0;margin: 0;border:0">
                   <input type="text" id="status"  style="width: 0;height: 0;padding: 0;margin: 0;border:0">
                 </div>
               </div>
               <div class="form-group">
                 <label class="col-sm-2 control-label">项目封面</label>
                 <div class="col-sm-8">
                     <input id="uploadImg1" type="file" class="file" data-preview-file-type="text">
                     <input type="text" value="" id="logo1" name="logo" style="height:0px;border:0px;margin:0px;padding:0px">
                    
                 </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">项目描述</label>
                <div class="col-sm-8">
                    <textarea class="form-control" rows="3" placeholder="请输入项目的简短描述" name="desc" id="projectDesc"></textarea>
                  </div>
              </div>
              <div class="form-group">
                <label for="inputEmail3" class="col-sm-2 control-label">开始时间:</label>
                <div class="input-group date col-sm-8" style="padding-left:15px !important;padding-right:15px !important">
                  <div class="input-group-addon">
                    <i class="fa fa-calendar"></i>
                  </div>
                  <input type="text" class="form-control pull-right" id="datepicker">
                </div>
                <!-- /.input group -->
              </div>
              <div class="form-group">
                <label for="inputEmail3" class="col-sm-2 control-label">结束时间:</label>
                <div class="input-group date col-sm-8" style="padding-left:15px !important;padding-right:15px !important">
                  <div class="input-group-addon">
                    <i class="fa fa-calendar"></i>
                  </div>
                  <input type="text" class="form-control pull-right" id="datepicker2">
                </div>
                <!-- /.input group -->
              </div>
             </div>
             <!-- /.box-body -->
             <div class="box-footer">
               <button type="button" class="btn btn-info pull-right" id="lanuchs"  onclick="updates1('0')">确认更改</button>
             </div>
             <!-- /.box-footer -->
           </form>
     </div>
        </div>
        <!-- /.box-body -->
        <!-- <div class="box-footer">
          <button type="button" class="btn btn-info pull-right" id="lanuchs"  onclick="submits('0')">保存</button>
         <button type="button" class="btn btn-warning pull-middle" id="lanuch"  onclick="submits('1')">发布</button>
        </div> -->
			</div>
			<!-- <div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭
				</button>
				<button type="button" class="btn btn-primary">
					提交更改
				</button>
			</div> -->
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>
  
  </div>
</section>
  


<script>
     $(document).ready(function() {
      var i = 0;
    var table =  $("#example2").DataTable({
      "bJQueryUI":true,
      "PaginationType" : "full_numbers", //详细分页组，可以支持直接跳转到某页
      stripeClasses: ["odd", "even"], //为奇偶行加上样式，兼容不支持CSS伪类的场合SS
     "aLengthMenu": [2, 3, 5,10,-1],//设置每页显示数据条数的下拉选项
      "sAjaxSource": localhost+'/manproject/project',
      "aaSorting": [[4, "asc"]],
      "aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0 ] },
                        { "bSortable": false, "aTargets": [ 1 ] },
                        { "bSortable": false, "aTargets": [ 2 ] },
                        { "bSortable": false, "aTargets": [ 3 ]},
                        { "bSortable": false, "aTargets": [ 5 ]},
                        { "bSortable": false, "aTargets": [ 6 ]}],  
      "columns": [
          {"data": null},
          { 
              "data": "projectTitle",
              "bSort": false ,
          },
          { 
              "data": "status",
               sWidth:"50px",
              "bSort": false ,
              "render": function (data, type, full, callback) {
                        //类型：0导航菜单；1操作按钮。
                        switch (data) {
                            case 0: return "未发布"; break;
                            case 1: return "发布 "; break;
                        }
                    }
          },
          { 
              "data": "startTime",
              "bSort": true,
          },
          { 
              "data": "endTime",
              "bSort": true,
          },
          { 
              "data": "projectUrl",
              "bSort": false ,
              render:function(data){
                  return '<img src= '+data+'  style=" width:50px;height:50px">'
                  console.log(data)
              }
          },
          { 
              "data": "ctime",
              sWidth:"100px",
              "render": function ChangeDateFormat(cellval) {
                            var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
                            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
                            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                            var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                            var seconds = date.getSeconds()< 10 ? "0" + date.getSeconds() :date.getSeconds();
                            var minutes = date.getMinutes()< 10 ? "0" + date.getMinutes() :date.getMinutes();
                            return date.getFullYear() + "-" + month + "-" + currentDate+ "-" + hours +':' +minutes+':'+seconds ;
                        }
          },
          { 
            "bSort": false ,
            render:function(data){
                  return "<button class='btn btn-success' id='edit' data-toggle='modal' data-target='#editArticle'>编辑</button><button class='btn btn-warning' style='margin-left:5px' id='dele'>删除</button> "
              }
          },
          { 
            "visible": false ,
            render:function(data){
                  return "<button class='btn btn-success' id='edit' data-toggle='modal' data-target='#editArticle'>编辑</button><button class='btn btn-warning' style='margin-left:5px' id='dele'>删除</button> "
              }
          },
        ],
        "fnRowCallback": function( row, data, index ) {
        
        if ( data.status == "1" ) {
           console.log('p1')
              $('td:eq(2)', row).html( '<p style="color:green">已发布</p>' );
        }else if(data.status == "0"){
              var button = $('td:eq(6)',row).children('#lanuch').length
              console.log(button)
              if(button == '0'){
                $('td:eq(2)', row).html( '<p style="color:blue">未发布</p>' );
                $('td:eq(6)', row).append( "<button style='margin-left:5px' type='button' class='btn btn-info ' id='lanuch' onclick='lanuch(1)'>发布</button>" );
              }
            }
          
            $('td:eq(0)', row).html( index+1);
          },
          fnInitComplete:function(){
           i==0
          },
         
        oLanguage: {
                    sProcessing : "",
                    sLengthMenu : "每页显示 _MENU_ 条记录",
                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                    sZeroRecords : "没有数据！",
                    sEmptyTable : "表中无数据存在！",
                    sInfo : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
                    sInfoEmpty : "表中无数据！",
                    sInfoFiltered : "",
                    sInfoPostFix: "",
                    sSearch: "搜索:",
                    sUrl: "",
                    sLoadingRecords: "载入中...",
                    sInfoThousands: ",",
                    oPaginate : {
                        "sFirst" : "首页",
                        "sPrevious" : "上一页",
                        "sNext" : "下一页",
                        "sLast" : "末页"
                    }
         },
       
       });
       　$("tbody").on('click', '#dele', function (data) {
        var data = table.row($(this).parents('tr')).data();
        swal.fire({
                    type: 'warning',
                    title: '确定要删除吗！',
                    showCloseButton: true,
                    showCancelButton: true,
                    focusConfirm: true,
                })
                .then((result) => {
                        if (result.value) {
                            $.post(localhost+"/manproject/projectdel", { //jq的post方法
                                      status:'3',
                                      id:data._id,
                                     
                                  }, function(res) {
                                      swal.fire({
                                          type: res.type,
                                          title: res.message,
                                      })
                                      .then((result) => {
                                              if (result.value) {
                                                    $('.content-wrapper').load(localhost +'/manproject');
                                                }else{

                                                }
                                              }
                                          );  
                                  })
                          }
                        }
                    );  
       })
       　$("tbody").on('click', '#lanuch', function (data) {
        var data = table.row($(this).parents('tr')).data();
        swal.fire({
                    type: 'warning',
                    title: '确定要发布吗！',
                    showCloseButton: true,
                    showCancelButton: true,
                    focusConfirm: true,
                    inputAttributes: {
                      autocapitalize: 'off'
                    },
                })
                .then((result) => {
                        if (result.value) {
                            $.post(localhost+"/manproject/projectdel", { //jq的post方法
                                      status:'1',
                                      id:data._id,

                                  }, function(res) {
                                      swal.fire({
                                          type: res.type,
                                          title: res.message
                                      })
                                      .then((value) => {
                                              switch (value) {
                                                  default:
                                                   
                                                    $('.content-wrapper').load(localhost +'/manproject');
                                                }
                                              }
                                          );  
                                  })
                          }
                        }
                    );  
       })

　　　　$("tbody").on('click', '#edit', function () {
        　　var data = table.row($(this).parents('tr')).data(); 
        console.log(data) //获取本行数据  数组形式
            $('#projectTitle').val(data.projectTitle)
            $('#logo1').val(data.projectUrl)
            $('#projectId').val(data.projectMark)
            $('#projectDesc').val(data.projectDesc)
            $('#datepicker').val(data.startTime)
            $('#datepicker2').val(data.endTime)
            initFileInput();
        })
            table.on('page.dt',()=>{
              console.log()
              if(i!=0){
                i==0
              }
            })
          });
          function lanuch(){

       }
          function initFileInput() {
    var url = $('#logo1').val()
    console.log(url)
      $("#uploadImg1").fileinput({
          initialPreviewAsData: true,  
          initialPreviewFileType: 'image',  
          initialPreview:url,
          language: 'zh', //设置语言
          dropZoneTitle: '可以将图片拖放到这里 …支持多文件上传',
          uploadUrl: localhost+'/manproject/addimage', //上传的地址
          uploadExtraData: function(previewId, index) {   //该插件可以向您的服务器方法发送附加数据。这可以通过uploadExtraData在键值对中设置为关联数组对象来完成。所以如果你有设置uploadExtraData={id:'kv-1'}，在PHP中你可以读取这些数据$_POST['id']
           ids =  $('#id').val()
          // var id = ids == null || undefined || '' ? 'imgs123': ids;
          
              return {seriesId: ids};
          },
          allowedFileExtensions: ['jpg','png'],//接收的文件后缀
          uploadAsync: true, //默认异步上传
          showUpload: true, //是否显示上传按钮
          showRemove: true, //显示移除按钮
          showPreview: true, //是否显示预览
          showCancel:true,   //是否显示文件上传取消按钮。默认为true。只有在AJAX上传过程中，才会启用和显示
          showCaption: false,//是否显示文件标题，默认为true
          browseClass: "btn btn-primary", //文件选择器/浏览按钮的CSS类。默认为btn btn-primary
          dropZoneEnabled: false,//是否显示拖拽区域
          minImageWidth: 50, //图片的最小宽度
          minImageHeight: 50,//图片的最小高度
          maxImageWidth: 5000,//图片的最大宽度
          maxImageHeight: 5000,//图片的最大高度
          maxFileSize: 0,//单位为kb，如果为0表示不限制文件大小
          minFileCount: 1, //每次上传允许的最少文件数。如果设置为0，则表示文件数是可选的。默认为0
          maxFileCount: 0, //每次上传允许的最大文件数。如果设置为0，则表示允许的文件数是无限制的。默认为0
          previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",//当检测到用于预览的不可读文件类型时，将在每个预览文件缩略图中显示的图标。默认为<i class="glyphicon glyphicon-file"></i>  
          layoutTemplates:{
              actionUpload:'',//去除上传预览缩略图中的上传图片
              actionZoom:'',   //去除上传预览缩略图中的查看详情预览的缩略图标
              actionDownload:'', //去除上传预览缩略图中的下载图标
              actionDelete:'', //去除上传预览的缩略图中的删除图标
          },//对象用于渲染布局的每个部分的模板配置。您可以设置以下模板来控制窗口小部件布局.eg:去除上传图标
          msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",//字符串，当文件数超过设置的最大计数时显示的消息 maxFileCount。默认为：选择上传的文件数（{n}）超出了允许的最大限制{m}。请重试您的上传！
      }).on('filebatchpreupload', function(event, data) { //该方法将在上传之前触发
          var id = $('#id option:selected').val();
          if(id == 0){
              return {
                  message: "请选择", // 验证错误信息在上传前要显示。如果设置了这个设置，插件会在调用时自动中止上传，并将其显示为错误消息。您可以使用此属性来读取文件并执行自己的自定义验证
                  data:{id : $('#id').val()} // any other data to send that can be referred in `filecustomerror`
              };
          }
      });
      $('#input-id').on('filesuccessremove', function(event, id) {  
    
});  
$('#input-id').on('filepredelete', function(event, key) {  
    console.log('Key = ' + key);  
});  
  }
</script>
<script type="text/javascript">

  function updates1 (data){
                              var flag=true //验证是否通过true/false
                              console.log(flag)
                              if(flag){
                                projectMark = $('#projectId').val()
                                  // console.log(cookie_value)
                                  projectTitle = $('#projectTitle').val()
                                  projectUrl =  $('#logo1').val()
                                  startTime = $('#datepicker').val()
                                  endTime = $('#datepicker2').val()
                                  projectDesc=$('#projectDesc').val()
                                  $.post(localhost+"/manproject/projectupdate", { //jq的post方法
                                      projectTitle:projectTitle,
                                      projectMark:projectMark,
                                      startTime:startTime,
                                      endTime:endTime,
                                      projectDesc:projectDesc
                                  }, function(res) {
                                      swal.fire({
                                          type: res.type,
                                          title: res.message
                                      })
                                      .then((value) => {
                                              switch (value) {
                                                  default:
                                                    $('#editArticle').modal('hide');
                                                    $(".modal-backdrop.fade").hide();
                                                    $('.content-wrapper').load(localhost +'/manproject');
     
                                                }
                                              }
                                          );  
                                  })
                                 
                              }else{
                                  Toast.fire({
                                          type: 'info',
                                          title: '请完善文章信息'
                                      })
                              }
                          };
   const Toast = Swal.mixin({
        toast: true,
        position: 'middle',
        showConfirmButton: false,
        timer: 3000
      });
  $(document).ready(function() {
      
      $(".select2").select2();
     
  $("#forms").submit(function(e){ //uploadVideoForm为表单名称
     e.preventDefault()
  });
            
  function imgSrcToBase64(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img,0,0,img.width,img.height);
      return canvas.toDataURL();
  }
      // bootstrap fileinput
  //fileuploaded此事件仅针对ajax上传触发，并在每个缩略图文件上传完成后触发。此事件仅针对ajax上传并在以下情况下触发：当点击每个预览缩略图中的上传图标并且文件上传成功时，或者当你有 uploadAsync设置为true您已触发批量上传。在这种情况下，fileuploaded每一个人选择的文件被上传成功后，触发事件。
  var id_str = 1;
  $('#uploadImg1').on('fileuploaded', function(event, data, previewId, index) {
      var val = data.response
      if(val){
         console.log(data.response)
         $('#logo1').val(val)
         var val =  $('#logo1').val()
      
      }
  });
  // filebatchuploadcomplete此事件仅在ajax上传和完成同步或异步ajax批量上传后触发。
  });
  </script>
<style>
  tfoot input th {
        width: 100%;
        padding: 3px;
        box-sizing: border-box;
        vertical-align: middle !important;
    }
    .table>tbody>tr>td {
        text-align:center;
        vertical-align: middle !important;
    }
    .table>thead:first-child>tr:first-child>th{
        text-align:center;
    }
    #example2{
      width:100% !important
    }
    .example2_wrapper{
      overflow: hidden;
    }
</style>
</body>
</html>
